package org.xjtu.weteam.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.JwtException;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.xjtu.weteam.common.JsonResponse;
import org.xjtu.weteam.common.utils.TokenUtils;
import org.xjtu.weteam.model.domain.User;
import org.xjtu.weteam.service.UserService;

import java.io.IOException;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * @author Kevin
 */

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    private final String appid = "wx82a83527e8050c88";
    private final String secret = "47602b81598f87042c1395bf4dc64b30";

    private final ObjectMapper objectMapper = new ObjectMapper(); // Jackson 对象

    @PostMapping("/login")
    public JsonResponse login(@RequestBody LoginRequest loginRequest) {
        String code = loginRequest.getCode();

        // 构建请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        // 使用 RestTemplate 发送请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
//        System.out.println("session: " + response);

        // 解析 session
        UserSession session = parseSession(response);
        if (session != null && session.getOpenid() != null) {
            // 检查用户是否存在，不存在则保存
            User user = userService.findByOpenid(session.getOpenid());
            if (user == null) {
                user = new User();
                user.setOpenId(session.getOpenid());
                user.setNickname("临时用户"+generateMixedChars());
                userService.insertByOpenId(user);
                user = userService.findByOpenid(session.getOpenid());
            }

            // 生成 token
            String token = TokenUtils.generateToken(user.getUserId());

//            //示例
//            UserSession userSession = (UserSession) SessionUtils.session().getAttribute("userSession");
//            if (userSession != null) {
//                // 使用 userSession 信息
//                System.out.println("User OpenID: " + userSession.getOpenid());
//            } else {
//                // 处理未登录的情况
//                System.out.println("用户未登录或会话已过期");
//            }

            return JsonResponse.success(token, "ok");
        }

        return JsonResponse.failure("Login failed");
    }

    private UserSession parseSession(String response) {
        try {
            // 将 JSON 字符串解析为 UserSession 对象
            return objectMapper.readValue(response, UserSession.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Data
    private static class LoginRequest {
        private String code;
    }

    @Data
    @AllArgsConstructor
    private static class LoginResponse {
        private String token;
    }

    @Data
    private static class UserSession {
        private String openid;
        private String session_key;
    }


    @PostMapping("/isValid")
    public ResponseEntity<?> isValid(@RequestHeader("token") String token) {
        if(token.isEmpty() || token.equals(" ")){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("error");
        }
        try {
            if (TokenUtils.isOutdated(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Token has expired");
            }
            String refreshedToken = TokenUtils.RefreshToken(token);

            // 返回一个结构化的响应体，包含新token
            Map<String, String> response = new HashMap<>();
            response.put("status", "Token is valid");
            response.put("refreshedToken", refreshedToken);

            return ResponseEntity.ok(response);

        } catch (JwtException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token");
        }
    }

    private String generateMixedChars() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }

        return sb.toString();
    }

}
